"ui";
(function(){
    function banhua_ui () {
        //初始化UI内部存储
        this.storage = null;

        //初始化项目XML文本
        this.xmls = "";

        this.version = "0.1.5";
    }

    banhua_ui.prototype.init = function (uiConfig, lables) {
        this.init = "班花模板初始化";
        //初始化banhua_ui
        if (!uiConfig) throw "请输入关键参数uiConfig";
        if (typeof(uiConfig) != "object") throw "您输入的参数类型不正确";
        
        if (!lables) throw "请输入关键参数lables";
        if (typeof(lables) != "object") throw "您输入lables参数类型不正确";

        this.storage = storages.create(uiConfig.title || "BanHua");

        // this.uiConfig = uiConfig;
        this.title = uiConfig.title || "我的脚本";
        this.color = uiConfig.color || "#FFC0CB";
        //副标题
        this.subtitle = uiConfig.subtitle || "";
        
        if (!ui.isUiThread()) throw "UI初始化只允许在UI线程中运行";
        // log(this.title);
        ui.layout(
            <RelativeLayout w='*' id='banhua' h='*'>
                <fab layout_alignParentBottom='true' id='end' margin='15dp' layout_width='wrap_content' layout_height='wrap_content' backgroundTint={this.color} elevation='5dp' src="@drawable/ic_power_settings_new_black_48dp" color={this.color}></fab>
                <fab layout_alignParentBottom='true' layout_alignParentRight='true' id='start' margin='15dp' layout_width='wrap_content' layout_height='wrap_content' backgroundTint={this.color} elevation='5dp' src="@drawable/ic_send_black_48dp" color={this.color}></fab>
                <appbar id='head' bg={this.color} w='*'>
                    <toolbar id='toolbar' title={this.title} w='*' subtitle={this.subtitle}>
                        <Switch id='autoService' layout_gravity='right' text='无障碍' textColor='#ffffff' padding='8dp' textSize='15sp' checked='{{auto.service != null}}'></Switch>
                    </toolbar>
                    <tabs id='tabs' tabIndicatorColor='#ffffff'></tabs>
                </appbar>
            </RelativeLayout>
        );
        let xmls = "<viewpager layout_below='head' layout_above='footer' id='viewpager'>";
        lables.forEach((name) => {
            xmls = xmls + "<LinearLayout w='*' h='*' padding='0 0 0 10' id='"+name+"' orientation='vertical'></LinearLayout>"
        });
        xmls = xmls + "</viewpager>";

        this.add_view(xmls, ui.banhua, true);

        this.add_view(
            <LinearLayout id='footer' layout_alignParentBottom='true' orientation='vertical' h='auto' w='*'>
                <text w='*' text='©️2019-2021 BanHua. All Rights Reserved' gravity='center'></text>
            </LinearLayout>, ui.banhua, true
        )

        //设置状态栏颜色
        ui.statusBarColor(this.color);
        //设置标签页
        ui.viewpager.setTitles(lables);
        //绑定标签栏
        ui.tabs.setupWithViewPager(ui.viewpager);

        //无障碍服务单击事件
        ui.autoService.on('click', () => {
            ui.autoService.isChecked() ? auto.service == null ? app.startActivity({action: "android.settings.ACCESSIBILITY_SETTINGS"}) : log('无障碍处于打开状态') : auto.service == null ? log('无障碍处于关闭状态') : auto.service.disableSelf();
        });

        //回到本界面时，触发resume事件
        ui.emitter.on('resume', ()=> {
            log("欢迎回来！");
            auto.service == null ? ui.autoService.setChecked(false) : ui.autoService.setChecked(true);
        });

    }

    banhua_ui.prototype.add_view = function (xml, page, zt) {
        this.xmls = this.xmls + xml;
        return ui.inflate(xml, page, zt);
    }

    banhua_ui.prototype.add_card = function (page, xml) {
        if (!page) throw "请输入page参数"; 
        if (!xml) throw "请输入xml参数";

        cardStr = <card h='auto' w='*' cardCornerRadius='10dp' margin='10 10 10 0' cardElevation='5dp'>
            {xml}
        </card>
        this.add_view(cardStr, page, true);
        this.ui_data = this.ui_data + xml;
    }


    //获取xml所有的bh_id的控件
    banhua_ui.prototype.get_xml_id = function (idName ,xml) {
        let re = new RegExp(idName+"[_0-9a-zA-Z]+[\'$\"$]", "g");
        let idArr = [];
        let arr = xml.match(re);
        for (idn in arr) {
            idArr.push(arr[idn].replace(/['"]/g, ""));
        }
        print("idArr:"+idArr);
        return idArr;
    }

    //保存指定id数组的控件内容到本地储存
    banhua_ui.prototype.putUiConfig = function (ids) {
        if (!this.storage) throw "本地储存变量不存在";

        
        ids.forEach((idName) => {
            print("【putUiConfig】\n正在写入【%s】", idName);
            if (ui[idName].toString().indexOf("EditText") > -1) {
                this.storage.put(idName, ui[idName].text());
            } else if (ui[idName].toString().indexOf("CheckBox") > -1) {
                this.storage.put(idName, ui[idName].isChecked());
            } else if (ui[idName].toString().indexOf("Spinner") > -1) {
                this.storage.put(idName, ui[idName].getSelectedItemPosition())
            } else if (ui[idName].toString().indexOf("Radio") > -1) {
                this.storage.put(idName, ui[idName].isChecked());
            } else {
                console.error("【%s】该类型的控件不支持保存", idName);
            }
        });
    }

    //设置界面中指定id内容      
    banhua_ui.prototype.setUiConfig = function (ids) {

        if (!this.storage) throw "本地储存变量不存在";
        ui.run(() => {
            ids.forEach((idName) => {
                // print("【setUiConfig】\n正在设置【%s】", idName);
                if (ui[idName].toString().indexOf("EditText") > -1) {
                    ui[idName].setText(this.storage.get(idName) || "");
                } else if (ui[idName].toString().indexOf("CheckBox") > -1) {
                    ui[idName].checked = this.storage.get(idName) || false;
                } else if (ui[idName].toString().indexOf("Spinner") > -1) {
                    ui[idName].setSelection(this.storage.get(idName) || 0);
                } else if (ui[idName].toString().indexOf("Radio") > -1) {
                    ui[idName].checked = this.storage.get(idName) || false;
                } else {
                    console.error("【%s】该类型的控件不支持设置控件信息", idName);
                }
            });
        });
    }

    //保存界面UI内容
    banhua_ui.prototype.put_ui = function () {
        let ids = this.get_xml_id("bh_", this.xmls);
        // log(ids);
        this.putUiConfig(ids);
    }

    //获取并设置界面UI内容
    banhua_ui.prototype.get_ui = function () {
        let ids = this.get_xml_id("bh_", this.xmls);
        // log(ids);
        this.setUiConfig(ids);
    }

    //班花会员框架生成
    banhua_ui.prototype.mod_userSystem = function (key, sok, page) {
        let storage = this.storage;
        
        //用户系统生成
        if (!paojiaoyun) throw "请先导入paojiaoyun模块";
        if (!key || !sok || !page) throw "key  sok page参数不得为空";
        

        if (typeof(key) != "string" || typeof(sok) != "string" || typeof(page) == "string") throw "key sok page参数类型不正确";
        //是否是会员
        paojiaoyun.isMember = false;
        //开始生成会员框架();
        paojiaoyun.init(key, sok);
        paojiaoyun._debug = () => {};

        //开始读取本地卡密 如果本地有卡密则登录
        let endTime = "00:00:00";

        if (storage.get("kami")) {
            paojiaoyun.SetCard(storage.get("kami"));
            let res = paojiaoyun.CardLogin();
            log("登录返回值："+JSON.stringify(res));
            if (res.code == 0) {
                toastLog("登录成功！");
                endTime = res.result.expires;
                paojiaoyun.isMember = true;
            } else {
                toastLog(res.code + "\n" +res.message);
                paojiaoyun.isMember = false;
                endTime = res.message;

            }
        } else {
            toastLog("未登录");
        }
        
        let xml = <vertical padding='5dp' w='*'>
            <horizontal padding='5dp' gravity='center_vertical' w='*'>
                <img w='30dp' h='30dp' scaleType='centerCrop' marginLeft='5dp' src='@drawable/ic_account_circle_black_48dp' tint={this.color}></img>
                <text marginLeft='5dp' text='设备ID：'></text>
                <text marginLeft='5dp' id='deid' text={paojiaoyun.getDeviceID()}></text>
            </horizontal>
            <horizontal padding='5dp' gravity='center_vertical' w='*'>
                <img w='30dp' h='30dp' scaleType='centerCrop' marginLeft='5dp' src='@drawable/ic_fingerprint_black_48dp' tint={this.color}></img>
                <text marginLeft='5dp' text='设备卡密：'></text>
                <text marginLeft='5dp' id='kami' text={storage.get("kami") || "暂无卡密"}></text>
            </horizontal>
            <horizontal padding='5dp' gravity='center_vertical' w='*'>
                <img w='30dp' h='30dp' scaleType='centerCrop' marginLeft='5dp' src='@drawable/ic_alarm_black_48dp' tint={this.color}></img>
                <text marginLeft='5dp' text='到期时间：'></text>
                <text marginLeft='5dp' id='endTime' text={endTime}></text>
            </horizontal>
            <horizontal gravity='center_vertical' w='*'>
                <button layout_weight='1' id='login' text='登 录' textSize='14sp' style='Widget.AppCompat.Button.Borderless'></button>
                <button layout_weight='1' id='test' text='试 用' textSize='14sp' style='Widget.AppCompat.Button.Borderless'></button>
                <button layout_weight='1' id='recharge' text='充 值' textSize='14sp' style='Widget.AppCompat.Button.Borderless'></button>
                <button layout_weight='1' id='out' text='退 出' textSize='14sp' style='Widget.AppCompat.Button.Borderless'></button>
            </horizontal>
        </vertical>
        this.add_card(page, xml);
        //登录事件


        let th = null;
        //卡密登录函数
        function login_click () {
            if (th != null && th.isAlive()) {
                toastLog("轻点,疼~");
            } else {
                th = threads.start(function(){
                    if (paojiaoyun.isMember) {
                        toastLog("您已登录，无需再登录");
                        return null;
                    }
                    toastLog("登 录");
                    dialogs.rawInput("请输入卡密：", "", (kamiStr) => {
                        log("输入的卡密是：%s", kamiStr);
                        if (!kamiStr || kamiStr == "" || typeof(kamiStr) != "string") {
                            toastLog("卡密格式不正确");
                        } else {
                            log("开始写入kami");
                            storage.put("kami", kamiStr);
                            log("开始登录");
                            paojiaoyun.SetCard(kamiStr);
                            let res = paojiaoyun.CardLogin();
                            log("登录返回值："+JSON.stringify(res));
                            let endTime;
                            if (res.code == 0) {
                                toastLog("登录成功！");
                                endTime = res.result.expires;
                                paojiaoyun.isMember = true;

                            } else {
                                toastLog(res.code + "\n" +res.message);
                                paojiaoyun.isMember = false;
                                endTime = res.message;
                            }
                            ui.run(() => {
                                ui.endTime.setText(endTime);
                                ui.kami.setText(kamiStr);
                            });
                        }
                    });
                });
            }
        }

        //试用登录函数
        function test_click () {
            if (th != null && th.isAlive()) {
                toastLog("轻点,疼~");
            } else {
                th = threads.start(function(){
                    if (paojiaoyun.isMember) {
                        toastLog("您已登录，无法试用");
                        return null;
                    }
                    toastLog("试用");
                    let res = paojiaoyun.TrialLogin();
                    let endTime = "00:00:00";
                    if (res.code == 0) {
                        toastLog("试用登录成功");
                        paojiaoyun.isMember = true;
                        endTime = res.result.expires;
                    } else {
                        toastLog(res.code + "\n" +res.message);
                        paojiaoyun.isMember = false;
                        endTime = res.message;
                    }

                    ui.run(() => {
                        ui.endTime.setText(endTime);
                        ui.kami.setText("试用登录");
                    });
                });
            }
        }

        //充值函数
        function recharge_click () {
            if (th != null && th.isAlive()) {
                toastLog("轻点,疼~");
            } else {
                th = threads.start(function(){
                    toastLog("充值");
                    if (!storage.get("kami")) {
                        toastLog("您没有可充值的卡密");
                        return null;
                    }
                    dialogs.rawInput("请输入卡密：", "", (kami) => {
                        if (kami != "") {
                            dialogs.confirm("确定要充值到："+storage.get("kami")+"吗?", "", (cz) => {
                                if (cz) {
                                    let endTime = "00:00:00";
                                    let res = paojiaoyun.CardRecharge(storage.get("kami"), kami);
                                    if (res.code == 0) {
                                        toastLog("充值成功，重新登录");

                                        paojiaoyun.SetCard(storage.get("kami"));
                                        let res = paojiaoyun.CardLogin();
                                        if (res.code == 0) {
                                            toastLog("重新登录成功");
                                            paojiaoyun.isMember = true;
                                            endTime = res.result.expires;
                                        } else {
                                            toastLog(res.code + "\n" +res.message);
                                            paojiaoyun.isMember = false;
                                        }
                                    } else {
                                        toastLog(res.code + "\n" +res.message);
                                    }

                                    ui.run(() => {
                                        ui.endTime.setText(endTime);
                                        ui.kami.setText(storage.get("kami"));
                                    });

                                } else {
                                    toastLog("充值取消");
                                }
                            });
                        }
                    });
                });
            }
        }

        //退出函数
        function out_click () {
            if (th != null && th.isAlive()) {
                toastLog("轻点,疼~");
            } else {
                th = threads.start(function(){
                    let endTime = "00:00:00", outStr = "null"
                    toastLog("退出");
                    let res = paojiaoyun.CardLogout();
                    if (res.code == 0) {
                        toastLog("退出登录成功");
                        outStr = "已退出";
                    } else {
                        toastLog(res.message);
                    }
                    storage.remove("kami");

                    ui.run(() => {
                        ui.endTime.setText(endTime);
                        ui.kami.setText(outStr);
                    });
                });
            }
        }

        //绑定卡密登录事件
        ui.login.on("click", login_click);
        //绑定试用登录事件
        ui.test.on("click", test_click);
        //绑定充值事件
        ui.recharge.on("click", recharge_click);
        //绑定退出事件
        ui.out.on("click", out_click);

        
    }

    banhua_ui.prototype.mod_drawXml = function  (title, uiArr, pg) {

        //在pg页面生成uiArr的UI
    
        //定义初始变量
        let cardXmlStart = "<card h=\'auto\' w=\'*\' cardCornerRadius=\'10dp\' margin=\'10 10 10 0\' cardElevation=\'5dp\'><vertical w=\'*\'><text text=\'"+title+"\' textColor=\'#ffffff\' bg=\'#FFC0CB\' textSize=\'16sp\' textType=\'bold\' padding=\'5dp\' gravity=\'center\'></text>";
        let cardXmlEnd = "</vertical></card>"
    
        let lineXmlStart = "<horizontal w=\'*\' padding=\'5dp\' gravity=\'center_vertical\'>";
        let lineXmlEnd = "</horizontal>";
    
        let items = "";
        uiArr.forEach((minArr) => {
            if (!minArr) return false;
            items = items + lineXmlStart;
            minArr.forEach((item, index) => {
                if (!item) return false;
                //转化项目属性
                //开始替换属性内容
                let prope = item.prope.trim().replace(/=/g, "=\'");
                prope = prope.replace(/\s/g, "\' ");
                // log(prope);
                items = items + "<" + item.class + " " + prope + "\'></" + item.class + ">"
            });
            // log(items);
            items = items + lineXmlEnd;
            // log(items)
        });
    
        let cardXml = cardXmlStart + items + cardXmlEnd;
        // log(cardXml);
    
        this.add_view(cardXml, pg, true);
    }
    
    
    this.banhua_ui = new banhua_ui();
})();